<template>
  <!-- 页面容器 -->
  <div class="page-container relative pb-20">
    <!-- 顶部导航栏 -->
    <header class="header sticky top-0 z-10 flex items-center bg-white shadow">
      <!-- 返回按钮 -->
      <button
          @click="router.back()"
          class="p-3 text-gray-600 hover:text-gray-900 transition-colors"
      >
        <i class="fas fa-arrow-left text-lg"></i>
      </button>
      <!-- 商家名称 -->
      <h1 class="flex-1 text-center font-bold text-gray-800">{{ businessInfo.name }}</h1>
      <!-- 右侧占位保持布局平衡 -->
      <div class="w-10"></div>
    </header>

    <!-- 加载指示器 -->
    <div v-if="loading" class="py-12 flex justify-center">
      <div class="w-8 h-8 border-4 border-primary-500 border-t-transparent rounded-full animate-spin"></div>
    </div>

    <!-- 主要内容区域 -->
    <div v-else>
      <!-- 商家Logo -->
      <div class="flex justify-center py-4 bg-white">
        <img
            :src="businessInfo.image"
            alt="饺子店招牌"
            class="w-24 h-24 rounded-lg object-cover shadow-lg transition-all duration-300 hover:shadow-xl"
        >
      </div>

      <!-- 商家信息 -->
      <div class="bg-white px-4 py-3 border-b border-gray-100">
        <h1 class="text-xl font-bold text-gray-800 mb-1">{{ businessInfo.name }}</h1>
        <p class="text-gray-600 mb-1">¥{{ businessInfo.minOrder }}起送 · ¥{{ businessInfo.deliveryFee }}配送</p>
        <p class="text-sm text-gray-500 flex items-center">
          <i class="fas fa-tag mr-1 text-primary-500"></i> {{ businessInfo.category }}
        </p>
      </div>

      <!-- 菜品列表 -->
      <div class="space-y-4 p-4">
        <!-- 单个菜品卡片 -->
        <div
            v-for="food in foods"
            :key="food.id"
            class="food-card bg-white rounded-lg p-4 shadow-sm transition-all duration-200 hover:shadow-md"
        >
          <div class="flex space-x-4">
            <!-- 菜品图片 -->
            <div class="relative">
              <img
                  :src="food.image"
                  :alt="food.name"
                  class="w-24 h-24 rounded-lg object-cover border border-gray-100 shadow"
                  @error="handleImageError"
              >
              <!-- 招牌标签 -->
              <div class="absolute top-2 right-2">
                <div v-if="food.popular" class="bg-red-500 text-white text-xs px-2 py-1 rounded-full flex items-center">
                  <i class="fas fa-star mr-1 text-xs"></i> 招牌
                </div>
              </div>
            </div>
            <!-- 菜品信息 -->
            <div class="flex-1 min-w-0">
              <h3 class="font-semibold text-gray-800 mb-1">{{ food.name }}</h3>
              <p class="text-sm text-gray-600 mb-2 line-clamp-2">{{ food.description }}</p>
              <!-- 价格信息 -->
              <p class="text-lg font-bold text-red-500 flex items-center">
                ¥{{ food.price }}
                <span v-if="food.originalPrice" class="ml-2 text-gray-400 text-sm line-through">¥{{ food.originalPrice }}</span>
              </p>
              <!-- 标签 -->
              <div class="mt-1">
                <span v-for="tag in food.tags" :key="tag" class="inline-block bg-gray-100 text-gray-600 text-xs px-2 py-0.5 rounded mr-1">
                  {{ tag }}
                </span>
              </div>
            </div>
            <!-- 数量控制 -->
            <div class="flex items-center space-x-3">
              <transition name="fade-scale">
                <div v-if="food.quantity > 0" class="flex items-center space-x-3">
                  <button
                      @click="decreaseQuantity(food.id)"
                      class="quantity-btn bg-gray-200 hover:bg-gray-300"
                  >
                    <i class="fas fa-minus"></i>
                  </button>
                  <span class="quantity-display">{{ food.quantity }}</span>
                </div>
              </transition>
              <button
                  @click="increaseQuantity(food.id)"
                  class="quantity-btn bg-primary-500 hover:bg-primary-600 text-white"
              >
                <i class="fas fa-plus"></i>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 购物车悬浮按钮 -->
    <transition name="slide-up">
      <div
          v-if="totalQuantity > 0"
          class="fixed bottom-16 left-1/2 transform -translate-x-1/2 w-full max-w-md px-4"
      >
        <div
            class="cart-container bg-gray-800 rounded-full flex items-center p-2 shadow-lg cursor-pointer"
            @click="showCartDetail = true"
        >
          <div class="flex items-center space-x-3 flex-1">
            <div class="relative">
              <div class="cart-icon">
                <i class="fas fa-shopping-cart text-white"></i>
                <transition name="pop">
                  <div
                      v-if="totalQuantity > 0"
                      class="cart-badge"
                  >
                    {{ totalQuantity }}
                  </div>
                </transition>
              </div>
            </div>
            <div class="text-white">
              <p class="font-semibold">¥{{ totalPrice.toFixed(2) }}</p>
              <p class="text-xs opacity-75">另需配送费¥{{ businessInfo.deliveryFee }}</p>
            </div>
          </div>
          <!-- 结算按钮 -->
          <button
              @click.stop="goToOrder"
              :disabled="!canCheckout"
              :class="[
                'px-6 py-2 rounded-full font-medium transition-colors duration-300',
                canCheckout
                  ? 'bg-green-500 hover:bg-green-600 text-white'
                  : 'bg-gray-600 text-gray-300 cursor-not-allowed'
              ]"
          >
            {{ canCheckout ? '去结算' : `¥${businessInfo.minOrder}起送` }}
          </button>
        </div>
      </div>
    </transition>

    <!-- 购物车详情弹窗 -->
    <transition name="fade">
      <div
          v-if="showCartDetail"
          class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-end"
          @click.self="showCartDetail = false"
      >
        <div class="w-full bg-white rounded-t-2xl max-w-md mx-auto max-h-[80vh] overflow-hidden">
          <!-- 购物车头部 -->
          <div class="p-4 border-b border-gray-200 flex justify-between items-center">
            <h2 class="text-lg font-bold">购物车</h2>
            <div class="text-sm text-gray-500">{{ totalQuantity }}件商品</div>
            <button @click="showCartDetail = false" class="text-gray-400 hover:text-gray-600">
              <i class="fas fa-times text-lg"></i>
            </button>
          </div>

          <!-- 购物车商品列表 -->
          <div class="overflow-y-auto max-h-[60vh]">
            <div
                v-for="food in cartItems"
                :key="food.id"
                class="p-4 border-b border-gray-100 flex items-center"
            >
              <img :src="food.image" class="w-16 h-16 rounded-md object-cover mr-3 border border-gray-100">
              <div class="flex-1 min-w-0">
                <h3 class="font-medium truncate">{{ food.name }}</h3>
                <p class="text-sm text-gray-500">¥{{ food.price }} × {{ food.quantity }}</p>
              </div>
              <div class="flex items-center">
                <p class="font-semibold">¥{{ (food.price * food.quantity).toFixed(2) }}</p>
                <!-- 数量增减按钮 -->
                <div class="ml-4 flex items-center space-x-2">
                  <button
                      @click="decreaseQuantity(food.id)"
                      class="quantity-btn bg-gray-200 hover:bg-gray-300"
                  >
                    <i class="fas fa-minus"></i>
                  </button>
                  <button
                      @click="increaseQuantity(food.id)"
                      class="quantity-btn bg-primary-500 hover:bg-primary-600 text-white"
                  >
                    <i class="fas fa-plus"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>

          <!-- 购物车底部结算 -->
          <div class="p-4 bg-white border-t border-gray-200">
            <div class="flex justify-between items-center mb-1">
              <span class="text-gray-600">商品总价</span>
              <span class="font-medium">¥{{ totalPrice.toFixed(2) }}</span>
            </div>
            <div class="flex justify-between items-center mb-1">
              <span class="text-gray-600">配送费</span>
              <span class="font-medium">¥{{ businessInfo.deliveryFee }}</span>
            </div>
            <div class="flex justify-between items-center mb-3 pt-2 border-t border-gray-100">
              <span class="font-semibold">总计</span>
              <span class="text-lg font-bold text-red-500">¥{{ (totalPrice + businessInfo.deliveryFee).toFixed(2) }}</span>
            </div>
            <!-- 结算按钮 -->
            <button
                @click="goToOrder"
                :disabled="!canCheckout"
                :class="[
                'w-full py-4 rounded-full font-medium transition-colors duration-300 text-lg',
                canCheckout
                  ? 'bg-green-500 hover:bg-green-600 text-white'
                  : 'bg-gray-200 text-gray-400 cursor-not-allowed'
              ]"
            >
              {{ canCheckout ? '去结算' : `差¥${(businessInfo.minOrder - totalPrice).toFixed(2)}起送` }}
            </button>
          </div>
        </div>
      </div>
    </transition>

    <!-- 底部导航栏 -->
    <FooterNav />
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import FooterNav from './FooterNav.vue'

import sp01 from '@/assets/sp/sp01.png'
import sp02 from '@/assets/sp/sp02.png'
import sp03 from '@/assets/sp/sp03.png'
import sp04 from '@/assets/sp/sp04.png'
import sp05 from '@/assets/sp/sp05.png'
import sp06 from '@/assets/sp/sp06.png'
import sj01 from '@/assets/sj/sj01.png'

const router = useRouter()

// 模拟加载状态
const loading = ref(true)
setTimeout(() => loading.value = false, 800)

// 商家信息
const businessInfo = ref({
  id: 1,
  name: '万家饺子（软件园E18店）',
  minOrder: 15,
  image: sj01, // 使用本地导入的商家Logo图片
  deliveryFee: 3,
  category: '饺子 · 东北菜'
})

// 菜品数据
const foods = ref([
  {
    id: 1,
    name: '纯肉鲜肉水饺',
    description: '精选新鲜猪肉为馅，手工擀皮，皮薄馅大，鲜香多汁',
    price: 18,
    originalPrice: 22,
    image: sp01,
    quantity: 0,
    popular: true,
    tags: ['招牌', '人气爆款']
  },
  {
    id: 2,
    name: '玉米鲜肉水饺',
    description: '新鲜玉米粒与猪肉完美搭配，清甜可口，老少皆宜',
    price: 20,
    image: sp02,
    quantity: 0,
    popular: true,
    tags: ['推荐']
  },
  {
    id: 3,
    name: '虾仁三鲜蒸饺',
    description: '虾仁、猪肉、豌豆精心调配，皮薄馅嫩，海鲜风味浓郁',
    price: 28,
    originalPrice: 35,
    image: sp03,
    quantity: 0,
    popular: false,
    tags: ['新品', '蒸饺']
  },
  {
    id: 4,
    name: '角瓜鸡蛋水饺',
    description: '角瓜丝搭配鸡蛋，清爽不腻，低脂健康之选',
    price: 16,
    image: sp04,
    quantity: 0,
    popular: false,
    tags: []
  },
  {
    id: 5,
    name: '小白菜猪肉水饺',
    description: '新鲜小白菜搭配精选猪肉，家常味道，清香爽口',
    price: 18,
    image: sp05,
    quantity: 0,
    popular: false,
    tags: []
  },
  {
    id: 6,
    name: '芹菜猪肉水饺',
    description: '爽脆芹菜与五花肉完美融合，清新开胃，地道东北味',
    price: 20,
    image: sp06,
    quantity: 0,
    popular: false,
    tags: []
  }
])

// 购物车数据
const cart = ref<Record<number, number>>({})
const showCartDetail = ref(false)

/**增加菜品数量
 * @param foodId 菜品ID
 */
const increaseQuantity = (foodId: number) => {
  const food = foods.value.find(f => f.id === foodId)
  if (food) {
    if (!cart.value[foodId]) {
      cart.value[foodId] = 0
    }
    cart.value[foodId] += 1
    food.quantity = cart.value[foodId]
  }
}

/**
 * 减少菜品数量
 * @param foodId 菜品ID
 */
const decreaseQuantity = (foodId: number) => {
  if (cart.value[foodId] > 0) {
    cart.value[foodId] -= 1
    const food = foods.value.find(f => f.id === foodId)
    if (food) {
      food.quantity = cart.value[foodId]
    }
  }
}

// 计算总数量
const totalQuantity = computed(() => {
  return Object.values(cart.value).reduce((sum, qty) => sum + qty, 0)
})

// 计算总价格
const totalPrice = computed(() => {
  return foods.value.reduce((sum, food) => {
    return sum + (food.price * (cart.value[food.id] || 0))
  }, 0)
})

// 购物车中的商品列表
const cartItems = computed(() => {
  return foods.value.filter(food => cart.value[food.id] > 0)
})

// 是否可以结算（是否达到起送价）
const canCheckout = computed(() => {
  return totalPrice.value >= businessInfo.value.minOrder
})

/**
 * 跳转到订单页面
 */
const goToOrder = () => {
  if (canCheckout.value) {
    router.push('/order')
  }
}

</script>

<style scoped>
/* 购物车徽章动画 */
@keyframes pop {
  0% { transform: scale(0); }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); }
}

/* 自定义样式 */
.header {
  @apply py-4 px-2 text-lg font-bold text-center bg-white shadow-sm;
}

/* 数量按钮样式 */
.quantity-btn {
  @apply w-8 h-8 rounded-full flex items-center justify-center transition-all duration-200;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.quantity-btn:active {
  transform: scale(0.95);
}

/* 数量显示样式 */
.quantity-display {
  @apply min-w-[24px] text-center font-semibold text-gray-800;
}

/* 购物车图标样式 */
.cart-icon {
  @apply w-12 h-12 bg-gray-700 rounded-full flex items-center justify-center relative;
}

/* 购物车徽章样式 */
.cart-badge {
  @apply absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full w-5 h-5 flex items-center justify-center;
  font-size: 0.7rem;
}

/* 购物车容器阴影 */
.cart-container {
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

/* 菜品卡片悬停效果 */
.food-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.1);
}
</style>